const vscode = require("vscode");
const { colors } = require("./webview/colors/colors");
const commands = {
    show: "extension-mir-script.showColorPicker"
}


class ColorCompletionItem extends vscode.CompletionItem {
    /**
     * 
     * @param {ColorType} color 
     */
    constructor(color) {
        super(color.number, vscode.CompletionItemKind.Color);
        this.detail = color.hex;
        this.documentation = color.number;
        this.insertText = color.number;
        this.filterText = color.number;
        this.sortText = color.number;
    }
}

class ColorsCompletionList extends vscode.CompletionList {
    /**
     * 
     * @param {ColorType[]} colors 
     */
    constructor(colors) {
        super(colors.map((color) => new ColorCompletionItem(color)), true);
    }
}


const ColorsCompletionItemProvider = {
    isCommandTriggered: false,
    triggerSuggest() {
        this.isCommandTriggered = true;
        // 执行两步操作：
        vscode.commands
            .executeCommand("editor.action.triggerSuggest")
            .then(() => {
                // 重置状态（延迟确保补全列表弹出）
                setTimeout(() => (this.isCommandTriggered = false), 500);
            });
    },
    validatorColorDocument(text) {
        const validators = [
            () => /color=\s*$/i.test(text),
            () => /autocolor=(\d+,)*$/i.test(text),
        ];
        return validators.some((validator) => validator());
    },
    provideCompletionItems(document, position) {
        const linePrefix = document.lineAt(position).text.slice(0, position.character);
        if (!this.validatorColorDocument(linePrefix) && !this.isCommandTriggered) {
            return undefined;
        }
        return new ColorsCompletionList(colors);
    },

}

class ColorQuickPicker {
    /**
     * 
     * @param {vscode.ExtensionContext} context 
     */
    static init(context) {
        context.subscriptions.push(
            vscode.languages.registerCompletionItemProvider("mirtxt", ColorsCompletionItemProvider, "=", ","),
            vscode.commands.registerCommand(commands.show, ColorsCompletionItemProvider.triggerSuggest)
        );
    }
}

module.exports = { ColorQuickPicker };